package com.datamanage.config;

import com.datamanage.user.entity.Company;
import com.datamanage.user.entity.Group;
import com.datamanage.user.entity.Permission;
import com.datamanage.user.entity.User;
import com.datamanage.user.repository.CompanyRepository;
import com.datamanage.user.repository.GroupRepository;
import com.datamanage.user.repository.PermissionRepository;
import com.datamanage.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class DataInitializer implements CommandLineRunner {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private GroupRepository groupRepository;
    
    @Autowired
    private PermissionRepository permissionRepository;
    
    @Autowired
    private CompanyRepository companyRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public void run(String... args) throws Exception {
        // 检查是否已有数据
        if (userRepository.count() == 0) {
            // 创建默认企业
            Company company = new Company();
            company.setName("默认企业");
            company.setDescription("系统默认企业");
            company = companyRepository.save(company);
            
            // 创建默认权限
            Permission permission1 = new Permission();
            permission1.setName("USER_READ");
            permission1.setDescription("用户读取权限");
            permissionRepository.save(permission1);
            
            Permission permission2 = new Permission();
            permission2.setName("USER_WRITE");
            permission2.setDescription("用户写入权限");
            permissionRepository.save(permission2);
            
            // 创建默认用户组
            Group group = new Group();
            group.setName("管理员组");
            group.setDescription("系统管理员用户组");
            group.getPermissions().add(permission1);
            group.getPermissions().add(permission2);
            group = groupRepository.save(group);
            
            // 创建默认用户
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setEmail("admin@example.com");
            admin.setCompany(company);
            admin.getGroups().add(group);
            userRepository.save(admin);
            
            System.out.println("初始数据已创建:");
            System.out.println("- 默认企业: " + company.getName());
            System.out.println("- 默认用户组: " + group.getName());
            System.out.println("- 默认用户: admin/admin123");
        }
    }
}